# 例1-2
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
from sklearn.manifold import TSNE


# 模拟两个语义相近的句子
sentence_1 = "猫 在 树上 睡觉"
sentence_2 = "猫 在 阳光下 打盹"

# 模拟词嵌入表示（假设每个单词的向量为随机生成）
np.random.seed(42)
word_embeddings = {
    "猫": np.random.rand(5),
    "在": np.random.rand(5),
    "树上": np.random.rand(5),
    "睡觉": np.random.rand(5),
    "阳光下": np.random.rand(5),
    "打盹": np.random.rand(5)
}


# 将句子表示为向量（简单取词向量的平均值）
def sentence_to_vector(sentence, embeddings):
    words = sentence.split(" ")
    print(words)
    vectors = [embeddings[word] for word in words if word in embeddings]
    return np.mean(vectors, axis=0)


vector_1 = sentence_to_vector(sentence_1, word_embeddings)
vector_2 = sentence_to_vector(sentence_2, word_embeddings)
print("句子1向量:", vector_1)
print("句子2向量:", vector_2)

# 计算欧氏距离和余弦相似度
# euclidean_dist = euclidean_distances([vector_1], [vector_2])
# cos_sim = cosine_similarity([vector_1], [vector_2])
# 欧氏距离: [[0.41084641]]
# 余弦相似度: [[0.92911994]]
euclidean_dist = euclidean_distances([vector_1], [vector_2])[0][0]
cos_sim = cosine_similarity([vector_1], [vector_2])[0][0]
# 欧氏距离: 0.41084640751084994
# 余弦相似度: 0.9291199410813494
print("欧氏距离:", euclidean_dist)
print("余弦相似度:", cos_sim)

# 使用t-SNE可视化嵌入空间（降维到2维）
tsne = TSNE(n_components=2, random_state=42, perplexity=1)
low_dim_embeddings = tsne.fit_transform(np.array([vector_1, vector_2]))
print("\n降维后的嵌入空间坐标:")
print("句子1:", low_dim_embeddings[0])
print("句子2:", low_dim_embeddings[1])


# 判断相似度计算的误差来源
def analyze_error(vector1, vector2):
    diff = np.abs(vector1 - vector2)
    max_error_dim = np.argmax(diff)
    return max_error_dim, diff[max_error_dim]


error_dim, error_value = analyze_error(vector_1, vector_2)
print("\n最大误差所在维度:", error_dim)
print("误差值:", error_value)
